package resolver

/*
Copyright 2021-2025 The k8gb Contributors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Generated by GoLic, for more details see: https://github.com/AbsaOSS/golic
*/

import (
	"context"

	"github.com/go-playground/validator/v10"

	k8gbv1beta1 "github.com/k8gb-io/k8gb/api/v1beta1"
	"sigs.k8s.io/controller-runtime/pkg/client"
)

type GslbResolver interface {
	// ResolveOperatorConfig executes once. It reads operator's configuration
	// from environment variables into &Config and validates
	ResolveOperatorConfig() (*Config, error)

	// ResolveGslbSpec fills Gslb by spec values. It executes always, when gslb is initialised.
	// If spec value is not defined, it will use the default value. Function returns error if input is invalid.
	ResolveGslbSpec(ctx context.Context, gslb *k8gbv1beta1.Gslb, client client.Client) error

	// GetDeprecations reads deprecation messages if any
	GetDeprecations() []string
}

type Resolver struct {
	spec            k8gbv1beta1.GslbSpec
	specValidator   *validator.Validate
	configValidator *validator.Validate
	errorSpec       error
}

// getValidator returns a singleton instance of specValidator.Validate with registered custom struct validations.
func getValidators() (specValidator *validator.Validate, configValidator *validator.Validate) {
	specValidator = validator.New()
	specValidator.RegisterStructValidation(ValidateStrategy, k8gbv1beta1.Strategy{})

	configValidator = validator.New(validator.WithRequiredStructEnabled())
	_ = configValidator.RegisterValidation("geotag", onlyLettersDigitsDash)
	_ = configValidator.RegisterValidation("unique", uniqueStrings)
	_ = configValidator.RegisterValidation("iphostport", isIPOrHostnameOrHostPort)
	configValidator.RegisterStructValidation(parentZoneOrFallbackRequired, Config{})
	configValidator.RegisterStructValidation(noMultipleProviders, Config{})
	configValidator.RegisterStructValidation(ValidateInfobloxStruct, Config{})
	return specValidator, configValidator
}

func NewResolver() *Resolver {
	r := &Resolver{}
	r.specValidator, r.configValidator = getValidators()
	return r
}
